import requests
import json
import base64
import re
import csv
from pathlib import Path

#先定义入第一行和第二行数据，也就是表头和答案。用于初始化写入output1.csv
data0 = list()
data0.append("姓名")
data1 = list()
data1.append("答案")

#读取答案.csv，并保存为list_daan，而且生成完整的第一行和第二行数据。
list_daan = list()
with open('答案.csv', 'r', encoding='utf-8') as f:
    # 遍历每一行数据
    for line in f:
        # 处理每一行数据
        row = line.strip().split(',')
        list_daan.append(row)
        data0.append(row[0]+row[1])
        data1.append(row[2])


text =  """" {"姓名": "张正锋", 
 "单选题": ["A", "A", "A", "A", "A", "A", "A", "A", "A", "A"], 
 "多选题": ["ABCDE", "ABCDE", "ABCDE", "ABCDE", "ABCDE", "ABCDE", "ABCDE", "ABCDE", "ABCDE", "ABCDE"],   
 "判断题": ["√", "√", "√", "√", "√", "√", "√", "√", "√", "√"]}""" 

DANXUAN_SCORE = 3
DUOXUAN_SCORE = 5
PANDUAN_SCORE = 2

pattern = r"\{.*?\}"
message_content = ""


# 打开文件并写入（encoding 建议用 utf-8-sig 兼容 Windows/Mac）
with open("output1.csv", "w", newline="", encoding="utf-8-sig") as f:
    # 创建 CSV 写入器
    writer = csv.writer(f)
    # 批量写入所有数据（也可用 writerow() 单行写入）
    writer.writerow(data0)
    writer.writerow(data1)

#转换图片为base64格式
def encode_image(image_path):
    """Encodes an image to base64 string."""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')
    
#把获取到的content字典格式转换成列表格式
def dist_lis(message_content):
    result = list()
    for i,j in message_content.items():
        if i in ["单选题","多选题","判断题"]:
            for index, value in enumerate(j):
                if value == "√":
                    value = "对"
                elif value == "×"or value == "X" or value == "╳":
                    value = "错"
                result.append([i,str(index+1),value])
    return result

#计算每一位考生的得分
def score(message_content,list_daan):
    danxuan_score = 0
    duoxuan_score = 0
    panduan_score = 0
    for i in message_content:
        if i in list_daan:
            if i[0] == "单选题":
                danxuan_score += DANXUAN_SCORE
            elif i[0] == "多选题":
                duoxuan_score += DUOXUAN_SCORE
            elif i[0] == "判断题":
                panduan_score += PANDUAN_SCORE
    # print(danxuan_score,duoxuan_score,panduan_score)
    return danxuan_score+duoxuan_score+panduan_score


def add_csv(message_content,name,daan):
    answer = [name,]
    score = [f"{name}得分",]
    for i in message_content:
        answer.append(i[2])    
        for j in daan:
            if i[0] == j[0] and i[1] == j[1]:
                if i[2] == j[2]:
                    if i[0] == "单选题":
                        score.append("3")
                    elif i[0] == "多选题":
                        score.append("5")
                    elif i[0] == "判断题":
                        score.append("2")
                else:
                    score.append("0")
                
    with open("output1.csv", "a", newline="", encoding="utf-8-sig") as f:
        writer = csv.writer(f)
        writer.writerow(answer)
        writer.writerow(score)

# 目标目录（绝对路径或相对路径均可）
target_dir = Path("./test")  # 相对路径（当前脚本所在目录下的 test_folder）
# target_dir = Path("/Users/xxx/Documents")  # 绝对路径（Mac/Linux）
# target_dir = Path("C:\\Users\\xxx\\Documents")  # 绝对路径（Windows，注意双反斜杠）

# 确保目录存在（可选，避免报错）
if not target_dir.exists() or not target_dir.is_dir():
    print(f"目录 {target_dir} 不存在或不是目录")
else:
    # 遍历目录下所有文件（不包含子目录），获取完整路径
    all_file_paths = [str(file) for file in target_dir.iterdir() if file.is_file() and file.suffix == ".jpg"]
    
url = "https://api.siliconflow.cn/v1/chat/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer sk-vpvqufobomtnxirzaxnhettzkykozcvljcyoewtmqovjgeau"
}    
for image_path in all_file_paths:
    encoded_image = encode_image(image_path)

    data = {
        "model": "Qwen/Qwen3-VL-32B-Instruct",
        # "model": "THUDM/GLM-4.1V-9B-Thinking",
        # "model": "Qwen/QwQ-32B",
        "messages": [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": f"你好，我上传的图片是一个考生做的题目，其中包含单选题，多选题，和判断题，麻烦你把考生姓名，单选题，多选题，判断题这四项信息打包成json文件返回给我。json格式参考{text}"},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{encoded_image}"
                        }
                    }
                ]
            }
        ],
        "max_tokens": 250,
        "stream": False,
    }

    # Send the request
    response = requests.post(url, headers=headers, data=json.dumps(data))

    # Check if request was successful
    if response.status_code == 200:
        # Parse the JSON response into a Python dictionary
        response_dict = response.json()
        
        # Extract the message content (the actual response from the model)
        try:
            # message_content = response_dict['choices'][0]['message']['content']
            message_content = response_dict['choices'][0]['message']['content']
            # print(message_content)
            
        except KeyError as e:
            print(f"Error extracting data from response: {e}")
            print("Full response:", response_dict)
    else:
        print(f"Request failed with status code: {response.status_code}")
        print("Response text:", response.text)
    
    #获取原始的message_content，获取完message_content是字符串格式。
    message_content = re.findall(pattern, message_content, flags=re.DOTALL)[0]
    #把message_content字符串转换成字典格式
    message_content = json.loads(message_content)
    name = message_content["姓名"]
    #转换成列表格式
    message_content = dist_lis(message_content)
    socres = score(message_content,list_daan)
    add_csv(message_content,name,list_daan)
    print(f"考生{name}的得分是{socres}")


